{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "614502df-4d38-4e28-92a4-b1fee72b1d4e",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "plt.rcParams['font.sans-serif'] = ['SimHei']\n",
    "plt.rcParams['axes.unicode_minus'] = False\n",
    "from sklearn.model_selection import train_test_split\n",
    "from sklearn.linear_model import LinearRegression\n",
    "from sklearn.metrics import mean_squared_error, r2_score\n",
    "from sklearn.preprocessing import StandardScaler"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "ae15ce09-2429-43a8-a6f3-9eefbd65873e",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>营业收入</th>\n",
       "      <th>营业成本</th>\n",
       "      <th>资产总计</th>\n",
       "      <th>负债合计</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>4607.372</td>\n",
       "      <td>3672.784</td>\n",
       "      <td>26765.302</td>\n",
       "      <td>9079.184</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>9167.268</td>\n",
       "      <td>8742.790</td>\n",
       "      <td>18491.371</td>\n",
       "      <td>10053.708</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>3953.762</td>\n",
       "      <td>1660.074</td>\n",
       "      <td>12881.135</td>\n",
       "      <td>3177.151</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>14131.196</td>\n",
       "      <td>9294.286</td>\n",
       "      <td>107272.203</td>\n",
       "      <td>67010.864</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>11047.016</td>\n",
       "      <td>9222.978</td>\n",
       "      <td>69480.531</td>\n",
       "      <td>27453.959</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "        营业收入      营业成本        资产总计       负债合计\n",
       "0   4607.372  3672.784   26765.302   9079.184\n",
       "1   9167.268  8742.790   18491.371  10053.708\n",
       "2   3953.762  1660.074   12881.135   3177.151\n",
       "3  14131.196  9294.286  107272.203  67010.864\n",
       "4  11047.016  9222.978   69480.531  27453.959"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#读入数据\n",
    "data = pd.read_excel('5.2.2数据.xlsx')\n",
    "data.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "b22a079c-0721-470b-8a9e-806c95179b37",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "截距项：-182.309\n",
      "回归系数：\n",
      "营业成本: 1.111\n",
      "资产总计: 0.197\n",
      "负债合计: -0.249\n"
     ]
    }
   ],
   "source": [
    "# 将数据分为特征和标签\n",
    "X = data.drop(columns=['营业收入'])\n",
    "y = data['营业收入']\n",
    "#数据集划分\n",
    "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
    "#线性回归模型训练\n",
    "lr = LinearRegression(fit_intercept=True)\n",
    "lr.fit(X_train, y_train)\n",
    "print(f\"截距项：{lr.intercept_:.3f}\")\n",
    "print(\"回归系数：\")\n",
    "for i, coef in enumerate(lr.coef_):\n",
    "    print(f\"{X_train.columns[i]}: {coef:.3f}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "3336210c-826a-4306-ad43-803c58ac9c0d",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "训练集MSE: 12976737.662\n",
      "测试集MSE: 51266843.001\n",
      "训练集R方: 0.998\n",
      "测试集R方: 0.996\n"
     ]
    }
   ],
   "source": [
    "#预测\n",
    "pred_train = lr.predict(X_train)\n",
    "pred_test = lr.predict(X_test)\n",
    "#模型性能度量\n",
    "mse_train = mean_squared_error(y_train, pred_train)\n",
    "r2_train = r2_score(y_train, pred_train)\n",
    "mse_test = mean_squared_error(y_test, pred_test)\n",
    "r2_test = r2_score(y_test, pred_test)\n",
    "# 存储结果到列表并打印\n",
    "results = [mse_train, mse_test, r2_train, r2_test]\n",
    "labels = ['训练集MSE', '测试集MSE', '训练集R方', '测试集R方']\n",
    "formatted_results = [\"{}: {:.3f}\".format(label, result) \n",
    "                     for label, result in zip(labels, results)]\n",
    "for result in formatted_results:\n",
    "    print(result)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "b32d3f82-be58-44cb-8548-51dc799309c8",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "标准化回归系数：\n",
      "营业成本: 69239.564\n",
      "资产总计: 20252.438\n",
      "负债合计: -17498.748\n"
     ]
    }
   ],
   "source": [
    "# 对特征进行标准化处理\n",
    "scaler = StandardScaler()\n",
    "X_train_scaled = scaler.fit_transform(X_train)\n",
    "\n",
    "# 拟合线性回归模型\n",
    "lr = LinearRegression()\n",
    "lr.fit(X_train_scaled, y_train)\n",
    "\n",
    "# 输出标准化回归系数\n",
    "print(\"标准化回归系数：\")\n",
    "for i, coef in enumerate(lr.coef_):\n",
    "    print(f\"{X_train.columns[i]}: {coef:.3f}\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
